package com.hishop.common.exception;

import com.hishop.common.ResponseCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJacksonJsonView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义包装全局异常，这样避免向客户端暴露服务器异常信息，泄露私密信息
 * 注意：自定义全局异常包装类要注入到spring容器当中
 * Created by hejie on 2018/3/19.
 */
@Slf4j
@Component
public class ExceptionResolver implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        log.error("{} exception", request.getRequestURI(), ex);
        //当使用jackson2.x的时候使用MappingJackson2JsonView，现在使用的
        ModelAndView modelAndView = new ModelAndView(new MappingJacksonJsonView());
        modelAndView.addObject("status", ResponseCode.ERROR.getCode());
        modelAndView.addObject("msg","接口异常，详情请查看服务端日志异常信息");
        modelAndView.addObject("data", ex.getMessage());
        return modelAndView;
    }
}
